const Service = require('../../../core/service/ApiService');

class StaffDao extends Service {

    //搜索服务人员信息
    async searchStaff(pn, ps, kw) {
        const searchOpt = {
            where: {
                status: this.constant.STAFF_STATUS.ENABLE
            },
            offset: (pn - 1) * ps,
            limit: ps,
            attributes: ['svc_staff_id', 'pic', 'name', 'phone', 'cur_month_svc_cnt', 'cur_month_svc_abn_cnt', 'score', 'status'],
            raw: true
        };
        if (kw) {
            searchOpt.where.name = {$like: this.model.literal(`%${kw}%`)};
        }
        return this.model.ServiceStaff.findAndCountAll(searchOpt);
    }

    //服务人员详细信息
    async getStaffDetail(id) {
        return this.model.ServiceStaff.findOne({
            where: {
                svc_staff_id: id,
                status: this.constant.STAFF_STATUS.ENABLE
            },
            attributes: ['svc_staff_id', 'pic', 'name', 'phone', 'birth', 'id_card_num', 'address', 'community_id_list'],
            raw: true
        })
    }

    //通过服务人员服务社区数组查找社区名
    async getCommunityName(arr_cmu_id) {
        return this.model.Community.findAll({
            where: {
                community_id: {
                    $in: arr_cmu_id
                }
            },
            attributes: ['community_id', 'name'],
            raw: true
        })
    }

    //查找服务人员信息
    async findStaffInfoById(id) {
        return this.model.ServiceStaff.findOne({
            where: {
                svc_staff_id: id,
                status: this.constant.STAFF_STATUS.ENABLE
            },
            attributes: ['svc_staff_id', 'phone'],
            raw: true
        })
    }

    //重置服务人员密码
    async resetPwd(id, encryptedPwd) {
        await this.model.ServiceStaff.update({
            pwd: encryptedPwd
        }, {
            where: {
                svc_staff_id: id,
                status: this.constant.STAFF_STATUS.ENABLE
            }
        })
    }

    //编辑服务人员信息
    async editStaffDetail(info) {
        await this.model.ServiceStaff.update(info, {
            where: {
                svc_staff_id: info.svc_staff_id
            }
        })
    }

    //添加服务人员
    async addSvcStaff(newInfo) {
        return this.model.ServiceStaff.create(newInfo)
    }

    //批量添加服务人员
    async importStaff(arrInfo) {
        return this.model.ServiceStaff.bulkCreate(arrInfo)
    }

    //删除服务人员(伪删除，状态值改为3)
    async deleteStaff(List) {
        this.model.ServiceStaff.update({
            status: this.constant.STAFF_STATUS.DELETE
        }, {
            where: {
                svc_staff_id: {
                    $in: List
                }
            }
        })
    }

    //修改服务人员状态
    async enableStaff(svc_staff_id, status) {
        return this.model.ServiceStaff.update({
            status: status
        }, {
            where: {
                svc_staff_id: svc_staff_id
            }
        })
    }
}

module.exports = StaffDao;

